<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%
    String path = request.getContextPath();
%>

<div id="material_edit_page" class="row-fluid" style="height: inherit;margin:0px">
    <form id="formInfoContent" class="form-horizontal" method="post" target="_ifr" style="border-bottom: solid 2px #3b73af;">
        <!-- 隐藏的越库单主键 -->
        <input type="hidden" id="id" name="id" value="${crossDock.id }" />
        <div  class="row" style="margin:0;padding:0;">
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="documentNoEdit" >越库单号：</label>
                <div class="controls">
                    <div class="required" >
                        <input type="text" id="documentNoEdit" class="span10" name="documentNo" value="${crossDock.documentNo }"  placeholder="后台自动生成" readonly="readonly" />
                    </div>
                </div>
            </div>
            <div class="control-group span6">
                <label class="control-label" for="areaIdEdit"> 库区：</label>
                <div class="controls">
                    <div class="required" style=" float: none !important;">
                        <select id="areaIdEdit" class="mySelect2 span10" name="areaId" value="${crossDock.areaId}" data-placeholder="请选择库区" >
                            <option value = ""></option>
                            <c:forEach items="${warehouse_list}" var="area">
                                <c:if test="${area.areaType == '0'}">
                                    <optgroup label="${area.warehouseName}">
                                        <c:forEach items="${warehouse_list}" var="area1">
                                            <c:if test="${area1.areaType == '1' && area1.parentId == area.id}">
                                                <option value="${area1.id}"  <c:if test="${crossDock.areaId==area1.id }">selected="selected"</c:if>>${area1.warehouseName}</option>
                                            </c:if>
                                        </c:forEach>
                                    </optgroup>
                                </c:if>
                            </c:forEach>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="row" style="margin:0;padding:0;">
            <div class="control-group span6">
                <label class="control-label" for="customerId">客户：</label>
                <div class="controls">
                    <div class="required" style=" float: none !important;">
                        <input type="hidden" id="customerId" name="customerId" value="${crossDock.customerId }">
                        <select class="mySelect2 span10" id="customerIdSelect" name="customerIdSelect" data-placeholder="请选择客户" style="margin-left:0px;">
                            <option value=""></option>
                            <c:forEach items="${customerlist}" var="customer">
                                <option value="${customer.id}" <c:if test="${crossDock.customerId==customer.id }">selected="selected"</c:if>>
                                        ${customer.shipper}
                                </option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
            </div>
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="outTime">越库时间：</label>
                <div class="controls">
                    <div class="required spa10">
                        <input class="form-control date-picker" id="outTime" name="outTime" type="text" value="${fn:substring(crossDock.outTime,0,19)}" placeholder="越库时间" class="span8" />
                    </div>
                </div>
            </div>
        </div>
        <div class="row" style="margin:0;padding:0;">
            <div class="control-group span6">
                <label class="control-label" for="outPlanId">越库计划：</label>
                <div class="controls">
                    <div class="required" style=" float: none !important;">
                        <input type="hidden" id="outPlanId" name="outPlanId" value="${crossDock.outPlanId }">
                        <select class="mySelect2 span10" style = "margin-left:0px;" id="outPlanIdSelect" name="outPlanIdSelect" data-placeholder="请选择越库计划">
                            <option value=""></option>
                            <c:forEach items="${outPlan}" var="customer">
                                <option value="${customer.id}" <c:if test="${crossDock.outPlanId==customer.id }">selected="selected"</c:if>>
                                        ${customer.planCode}
                                </option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
            </div>
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="userId" >移库操作人:</label>
                <div class="controls">
                    <div class="span12 required" >
                        <input type="text" id="userId" class="span10" name="userId" placeholder="请选择移库操作人" />
                    </div>
                </div>
            </div>
        </div>
        <div style="margin-bottom:5px;">
            <span class="btn btn-info" id="outformSave">
		       <i class="ace-icon fa fa-check bigger-110"></i>保存
            </span>
            <span class="btn btn-info" id="outformSubmit" onclick="outformSubmitBtn();">
		        <i class="ace-icon fa fa-check bigger-110"></i>&nbsp;提交
            </span>
        </div>
    </form>
    <!-- 入库单搜索div -->
    <div  id="materialDiv" style="margin:10px;">
        <!-- 下拉框搜索添加详情 -->
        <label class="inline" for="materialInfor">物料：</label>
        <input type="text" id="materialInfor" style="width:200px;margin-right:10px;"/>
        <button class="btn btn-xs btn-primary" onclick="addCrossDockMaterial();">
            <i class="glyphicon glyphicon-plus" style="margin-right:6px;"></i>添加
        </button>
    </div>
    <!-- 表格div -->
    <div id="grid-div-detail" style="width:100%;margin:0px auto;">
        <!-- 	表格工具栏 -->
        <div id="fixed_tool_div" class="fixed_tool_div detailToolBar">
            <div id="__toolbar__detail" style="float:left;overflow:hidden;"></div>
        </div>
        <!-- 入库单信息表格 -->
        <table id="grid-table-detail" style="width:100%;height:100%;"></table>
        <!-- 表格分页栏 -->
        <div id="grid-pager-detail"></div>
    </div>
</div>
<iframe src="about:blank" name="_ifr" height="0" class="hidden"></iframe>
<script type="text/javascript" src="<%=path%>/static/js/techbloom/wms/crossdock/crossdockmanage/crossDock_detail.js"></script>
<script type="text/javascript">
    var context_path = '<%=path%>';
    var oriData;      //表格数据
    var _grid;        //表格对象
    var selectData = 0;   //存放物料选择框中的值
    var selectParam = ""; //存放之前下拉框的查询结果

    $(".date-picker").datetimepicker({format : 'YYYY-MM-DD HH:mm:ss',useMinutes : true,useSeconds : true});

    //客户选择
    $("#formInfoContent #customerIdSelect").change(function(){
        $('#formInfoContent #customerId').val($('#formInfoContent #customerIdSelect').val());
    });
    //类型选择
    $("#formInfoContent #outstorageTypeEdit").change(function(){
        $('#formInfoContent #outstorageType').val($('#formInfoContent #outstorageTypeEdit').val());
    });
    //越库计划选择
    $("#formInfoContent #outPlanIdSelect").change(function(){
        $('#formInfoContent #outPlanId').val($('#formInfoContent #outPlanIdSelect').val());
    });

    $('#formInfoContent .mySelect2').select2();

    $('[data-rel=tooltip]').tooltip();

    $("#outformSave").click(function(){
        if($('#formInfoContent').valid()){
            //通过验证：获取表单数据，保存表单信息
            var formdata = $('#formInfoContent').serialize();
            saveFormInfo(formdata);
        }
    });

    $("#formInfoContent").validate({
        ignore: "",
        rules: {
            "areaId": {
                required: true,
            },
            "customerIdSelect": {
                required: true,
            },
            "outTime":{
                required: true,
            },
            "outPlanIdSelect":{
                required: true,
            },
            "userId":{
                required: true,
            },
        },
        messages: {
            "areaId": {
                required: "请选择库区",
            },
            "customerIdSelect": {
                required: "请选择客户",
            },
            "outTime":{
                required: "请选择越库时间",
            },
            "outPlanIdSelect":{
                required: "请选择越库计划",
            },
            "userId":{
                required: "请选择下架操作人",
            },
        },
        errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
        }
    })

    //工具栏
    $("#__toolbar__detail").iToolBar({
        id:"__tb__01",
        items:[
            {label:"删除", onclick:delOutStorageDetail}
        ]
    });

    //初始化表格
    _grid = $("#grid-table-detail").jqGrid({
        url : context_path+ '/crossDock/crossDockDetaillist?id='+ $("#formInfoContent #id").val()+"&outPlanId="+$("#formInfoContent #outPlanId").val(),
        datatype : "json",
        colNames : [ '越库主键','物料主键','详情主键', '物料编号', '物料名称','物料单位','可领数量', '数量', '单价'],
        onCellSelect : function(ts,ri,ci,tdHtml,e){
            if(ri !=10) {
                return;
            }
            var rowData =  $('#grid-table-detail').jqGrid('getRowData',ts);
            var routName=rowData.materialNo;
            $("#grid-table-detail").setColProp('batchNo',{editoptions:{value:getBatchNo(routName,$("#areaIdEdit").val())}});
        },
        colModel : [
            {name:'documentId',index:'documentId',width:20,hidden:true},
            {name:'materialId',index:'materialId',width:20,hidden:true},
            {name:'id',index:'id',width:20,hidden:true},
            {name:'materialNo',index:'materialName',width:20},
            {name:'materialName',index:'materialName',width:40},
            {name:'unit',index:'unit',width:20},
            {name:'avalibleAmount',index:'avalibleAmount',width:20},
            {name:'amount',index:'amount',width:20,editable: true,editrules:{custom: true, custom_func: numberRegex},
                editoptions: {
                    size: 25, dataEvents: [{
                        type: 'blur',
                        fn: function (e) {
                            var $element = e.currentTarget;
                            var $elementId = $element.id;
                            var rowid = $elementId.split("_")[0];
                            var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
                            if (!reg.test($("#" + $elementId).val())) {
                                layer.alert("非法的数量！(注：可以有两位小数的正实数)");
                                return;
                            }
                            var id = $("#grid-table-detail").jqGrid('getGridParam', 'selrow');
                            var rowData = $("#grid-table-detail").jqGrid('getRowData', id).avalibleAmount;
                            var materialId = $("#grid-table-detail").jqGrid('getRowData', id).materialId;
                            $.ajax({
                                type: "POST",
                                dataType: "json",
                                url: context_path + '/crossDock/saveamount',
                                data: {amount: $("#" + rowid + "_amount").val(), avalibleAmount: rowData,materialId:materialId, id: id,lastamount:lastamount},
                                success: function (data) {
                                    if(!data.result){
                                        layer.alert(data.msg);
                                    }
                                }
                            })
                        }
                    },
                        {
                            type: 'focus',
                            fn: function (e) {
                                var $element = e.currentTarget;
                                var $elementId = $element.id;
                                var rowid = $elementId.split("_")[0];
                                var aa = $("#" + rowid + "_amount").val();
                                if(aa!=""){
                                    lastamount = aa;
                                }
                            }
                        }

                    ]
                }
            },
            {name:'price',index:'price',width:20}
            /*{name :'methodId',index:'methodId',width:20,editable: true, edittype: "select",editoptions: {
                    value: getMethod(),
                    dataEvents:[{
                        type: 'blur',
                        fn: function (e) {
                            var $element = e.currentTarget;
                            var $elementId = $element.id;
                            var rowid = $elementId.split("_")[0];
                            var id=$("#grid-table-detail").jqGrid('getGridParam','selrow');
                            $.ajax({
                                type:"POST",
                                url:context_path+ '/crossDock/outDetailMethodEdit',
                                dataType:"json",
                                data:{detailId:id,methodId:$("#"+rowid+"_methodId").val()},
                                success:function(data){
                                    if(data.msg){

                                    }
                                    layer.alert(data.msg);
                                }
                            })
                        }
                    }]
                }
            },*/
            /*{name:'batchNo',index:'batchNo',width:20,editable: true, edittype: "select", editoptions:{
                    dataInit:function (e) {
                        var id  = $('#grid-table-detail').jqGrid('getGridParam','selrow');
                        var rowData =  $('#grid-table-detail').jqGrid('getRowData',id);
                        materialNo=rowData.materialNo;
                    },
                dataEvents:[{
                        type: 'blur',
                        fn: function (e) {
                            var $element = e.currentTarget;
                            var $elementId = $element.id;
                            var rowid = $elementId.split("_")[0];
                            var id=$("#grid-table-detail").jqGrid('getGridParam','selrow');
                            $.ajax({
                                url:context_path+ '/crossDock/saveBatchNo',
                                type:"POST",
                                dataType:"json",
                                data:{detailId:id,batchNo:$("#"+rowid+"_batchNo").val()},
                                success:function(data){
                                    layer.alert(data.msg);
                                }
                            })
                        }
                    }]
                }
            }*/
        ],
        rowNum : 20,
        rowList : [ 10, 20, 30 ],
        pager : '#grid-pager-detail',
        sortname : 'osd.ID',
        sortorder : "asc",
        altRows: true,
        viewrecords : true,
        autowidth:true,
        multiselect:true,
        multiboxonly: true,
        loadComplete : function(data){
            var table = this;
            setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
            oriData = data;
            $(window).triggerHandler('resize.jqGrid');
        },
        cellEdit: true,
        cellsubmit : "clientArray",
        emptyrecords: "没有相关记录",
        loadtext: "加载中...",
        pgtext : "页码 {0} / {1}页",
        recordtext: "显示 {0} - {1}共{2}条数据",
    });
    //在分页工具栏中添加按钮
    $("#grid-table-detail").navGrid("#grid-pager-detail",{edit:false,add:false,del:false,search:false,refresh:false}).navButtonAdd('#grid-pager-detail',{
            caption:"",
            buttonicon:"ace-icon fa fa-refresh green",
            onClickButton: function(){
                $("#grid-table-detail").jqGrid('setGridParam',
                    {
                        url:context_path + '/crossDock/crossDockDetaillist',
                        postData: {id:$("#formInfoContent #id").val(),outPlanId:$("#formInfoContent #outPlanId").val(),queryJsonString:""} //发送数据  :选中的节点
                    }
                ).trigger("reloadGrid");
            }
        });

    $(window).on("resize.jqGrid", function () {
        $("#grid-table-detail").jqGrid("setGridWidth", $("#grid-div-detail").width() - 3 );
        var height = $(".layui-layer-title",_grid.parents(".layui-layer")).height()+
                     $("#formInfoContent").outerHeight(true)+
                     $("#grid-pager-detail").outerHeight(true)+
                     $("#materialDiv").outerHeight(true)+
                     $("#fixed_tool_div.fixed_tool_div.detailToolBar").outerHeight(true)+
                   //$("#gview_grid-table-detail .ui-jqgrid-titlebar").outerHeight(true)+
                     $("#gview_grid-table-detail .ui-jqgrid-hbox").outerHeight(true);
                     $("#grid-table-detail").jqGrid("setGridHeight", _grid.parents(".layui-layer").height()-height);
    });

    var materialNo="";

    var lastamount = 0.00;

    //物料下拉框
    $("#materialInfor").select2({
        placeholder : "请选择物料",//文本框的提示信息
        minimumInputLength : 0, //至少输入n个字符，才去加载数据
        allowClear : true, //是否允许用户清除文本信息
        multiple: true,
        closeOnSelect:false,
        ajax : {
            url : context_path + '/crossDock/getmaterialList',
            dataType : 'json',
            delay : 250,
            data : function(term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                selectParam = term;
                return {
                    outPlanId : $("#formInfoContent #outPlanId").val(),
                    queryString : term, //联动查询的字符
                    pageSize : 15, //一次性加载的数据条数
                    pageNo : pageNo, //页码
                    time : new Date()
                    //测试
                }
            },
            results : function(data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results : res,
                        more : more
                    };
                } else {
                    return {
                        results : {
                            "id" : "0",
                            "text" : "没有更多结果"
                        }
                    };
                }
            },
            cache : true
        }
    })

    $('#materialInfor').on("change",function(e){
        var datas=$("#materialInfor").select2("val");
        selectData = datas;
        var selectSize = datas.length;
        if(selectSize>1){
            var $tags = $("#s2id_materialInfor .select2-choices");   //
            //$("#s2id_materialInfor").html(selectSize+"个被选中");
            var $choicelist = $tags.find(".select2-search-choice");
            var $clonedChoice = $choicelist[0];
            $tags.children(".select2-search-choice").remove();
            $tags.prepend($clonedChoice);

            $tags.find(".select2-search-choice").find("div").html(selectSize+"个被选中");
            $tags.find(".select2-search-choice").find("a").removeAttr("tabindex");
            $tags.find(".select2-search-choice").find("a").attr("href","#");
            $tags.find(".select2-search-choice").find("a").attr("onclick","removeChoice();");
        }
        //执行select的查询方法
        $("#materialInfor").select2("search",selectParam);
    });
    function removeChoice(){
        $("#s2id_materialInfor .select2-choices").children(".select2-search-choice").remove();
        $("#materialInfor").select2("val","");
        selectData = 0;
    }

    function getMethod(){
        var str ="";
        $.ajax({
            type: "post",
            async: false,
            url: context_path + "/crossDock/getMethod",
            dataType: "json",
            success: function (data) {
                if(data){
                    for (let i = 0; i < data.result.length; i++) {
                        str += data.result[i].id + ":" + data.result[i].methodName + ";";
                    }
                    str = str.substring(0, str.length - 1);
                }
            }
        })
        return str;
    }

    function getBatchNo(materialNo,areaId){
        var str = "";
        $.ajax({
            type:"post",
            async:false,
            url:context_path+"/crossDock/getBatchNo",
            data:{materialNo:materialNo,areaId:areaId},
            dataType:"json",
            success:function(data){
                if(data){console.dir(data);
                    for(let i =0;i<data.result.length;i++){
                        str += data.result[i].id + ":" + data.result[i].batchNo + ";";
                    }
                    str = str.substring(0,str.length - 1);
                }
            }
        })
        return str;
    }

    function outformSubmitBtn(){
        if($("#formInfoContent #id").val()==-1){
            layer.alert("请先保存单据");
            return;
        }else{
            // $("#formInfoContent #outformSubmit").attr("disabled","disabled");
            //后台修改对应的数据
            layer.confirm("确定提交,提交之后数据不能修改", function () {
                $.ajax({
                    type:"POST",
                    url:context_path+"/crossDock/setOutState",
                    dataType:"json",
                    data:{id:$('#formInfoContent #id').val(),outPlanId:$('#formInfoContent #outPlanId').val()},
                    success:function(data){
                        if(data.result){
                            layer.closeAll();
                            layer.msg("提交成功",{icon:1,time:1200});
                            gridReload();
                        }else{
                            layer.alert(data.msg);
                        }
                    }
                })
            });
        }
    }

    //数量输入验证
    function numberRegex(value, colname) {
        var regex = /^\d+\.?\d{0,2}$/;
        if (!regex.test(value)) {
            layer.alert("非法的数据,请输入整数");
            return [false, ""];
        }
        else  return [true, ""];
    }

    $("#userId").select2({
        placeholder: "请选择下架操作人",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/crossDock/getUser",
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    })

    if($('#formInfoContent #id').val()!=-1) {
        $.ajax({
            type: "POST",
            url: context_path + '/crossDock/getValueById',
            data: {id: $('#formInfoContent #id').val()},
            dataType: "json",
            success: function (data) {
                $("#userId").select2("data", {
                    id: data.userId,
                    text: data.userName
                });
            }
        })
    }
</script>